package com.example.orderprovider.dubbo;

import com.example.orderprovider.model.Order;
import com.example.orderprovider.service.IOrderService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.example.api.CouponApi;
import org.example.api.OrderApi;
import org.example.dto.CouponDto;
import org.example.dto.OrderDto;
import org.example.response.R;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;

/**
 * @author Kong
 * @date 2021-8-19 16:40
 */
@Slf4j
@DubboService
public class OrderDubboService implements OrderApi {
    @Autowired
    private IOrderService orderService;
    @DubboReference
    private CouponApi couponApi;
    @Override
    public R createOrder(OrderDto dto) {
        log.info("[AT模式]全局事务XID：{}",RootContext.getXID());
        Order order = new Order();
        order.setAmount(new BigDecimal(100));
        order.setCount(2);
        order.setOrderNo("20210819000001");
        order.setUserId(1);
        order.setProductCode("20210819000001");
        boolean rs = orderService.save(order);
        // 发送优惠券，用于验证A->B->C->D链路模式
        couponApi.issueCoupon(new CouponDto());
        if(rs) {
            return R.Builder.getInstance().buildOk().build();
        } else {
            return R.Builder.getInstance().buildFailure("订单创建失败").build();
        }
    }
}
